<template>
  <view class="router-view bcl-active pt-15">
    <view class="bcl-white">
      <uni-cell title="头像更换" @cellTap="updateAvatar">
        <view slot="value" class="uni-avatar">
          <image :src="userInfo.avatar || defaultImage" />
        </view>
      </uni-cell>
      <uni-cell title="昵称" url="/user/info/nickName">
        <view slot="value" class="nickname hide-text-1 text-right">{{
          userInfo.nickname || userInfo.name || ""
        }}</view>
      </uni-cell>
      <uni-cell title="性别" noPointer>
        <view slot="value" class="box-1">
          <picker @change="changeSex" :range="sex" class="width">
            <view style="width: 300upx; height: 100upx;" class="text-right">{{
              sex[sexId]
            }}</view>
          </picker>
        </view>
      </uni-cell>
      <uni-cell title="个人简介" url="/user/info/intro"></uni-cell>
    </view>
  </view>
</template>

<script>
import { mapState, mapActions } from "vuex";
import { chooseImage } from "@/utils/choose";
import { updateAvatar, editSex } from "@/apis/user";
import uniCell from "@/components/cell";

export default {
  components: {
    uniCell,
  },

  data() {
    return {
      defaultImage: this.$config.default,
      sex: ["女", "男"],
      sexId: 0,
    };
  },

  onShow() {
    if (this.userInfo.hasOwnProperty("sex")) this.sexId = this.userInfo.sex;
  },

  methods: {
    // 上传头像
    async updateAvatar() {
      let imgs = await chooseImage();

      let params = {
        avatar: imgs[0].url,
      };

      let { code, data } = await updateAvatar(params);
      if (code === 200) {
        this.$toast("更新成功");
        let userInfo = {
          ...this.userInfo,
          avatar: imgs[0].url,
        };
        this.SET_USER_INFO(userInfo);
      }
    },

    async changeSex(event) {
      this.sexId = event.target.value;
      let { code } = await editSex({ sex: this.sexId });
      if (code === 200) {
        this.$toast("修改成功");
        let userInfo = {
          ...this.userInfo,
          sex: this.sexId,
        };
        this.SET_USER_INFO(userInfo);
      }
    },

    ...mapActions(["SET_USER_INFO"]),
  },

  computed: {
    ...mapState(["userInfo"]),
  },
};
</script>

<style lang="scss" scoped>
.router-view {
  .nickname {
    width: 400upx;
  }
}
</style>
